<template>
  <div>
    <selector
      :is-show="isProvinceSelectorShow"
      default-title="请选择 - 省"
      code-key="provinceCode"
      @handle-change="handleProvinceChange"
      :data="provinces"
    ></selector>
    <selector
      :is-show="isCitySelectorShow"
      default-title="请选择 - 市"
      code-key="cityCode"
      @handle-change="handleCityChange"
      :data="state.cities"
    ></selector>
    <selector
      :is-show="isCountySelectorShow"
      default-title="请选择 - 区县"
      code-key="countyCode"
      @handle-change="handleCountyChange"
      :data="state.counties"
    ></selector>
  </div>
</template>

<script setup>
import Selector from "./components/Selector.vue";
import propsDefination from "./extends/props";

import {reactive, computed, toRaw} from "vue";

const props = defineProps(propsDefination);

const emit = defineEmits(["handleSelect"]);

const provinces = formatData(props.data);

const state = reactive({
  cities: null,
  counties: null,
  selectedInfo: {
    province: null,
    city: null,
    county: null,
  },
});

const isProvinceSelectorShow = computed(() => !!provinces);
const isCitySelectorShow = computed(() => !!state.cities);
const isCountySelectorShow = computed(() => !!state.counties);

const handleProvinceChange = (value) => {
  if (!value) {
    state.selectedInfo.province = null;
    state.selectedInfo.city = null;
    state.selectedInfo.county = null;
    state.cities = null;
    state.counties = null;
    return;
  }

  const [code, name] = value.split(":");

  state.selectedInfo.province = {
    code,
    name,
  };

  state.cities = provinces[name].cities;
};

const handleCityChange = (value) => {
  if (!value) {
    state.selectedInfo.city = null;
    state.selectedInfo.county = null;
    state.counties = null;
    return;
  }

  const [code, name] = value.split(":");

  state.selectedInfo.city = {
    code,
    name,
  };

  state.counties = state.cities[name].counties;
};

const handleCountyChange = (value) => {
  if (!value) {
    return;
  }

  const [code, name] = value.split(":");

  state.selectedInfo.county = {
    code,
    name,
  };

  emit("handleSelect", toRaw(state.selectedInfo));
};

function formatData(data) {
  return data.reduce((prev1, next1) => {
    next1.cities = next1.cities.reduce((prev2, next2) => {
      next2.counties = next2.counties.reduce((prev3, next3) => {
        prev3[next3.countyName] = next3;
        return prev3;
      }, {});

      prev2[next2.cityName] = next2;
      return prev2;
    }, {});

    prev1[next1.provinceName] = next1;
    return prev1;
  }, {});
}
</script>
